from rest_framework import serializers
from .models import User, Patient, RelationType, IdType, Sflogin, RechargeOrder, PaymentUrl
from decimal import Decimal


class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id','username', 'phone', 'avatar']


class RelationTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = RelationType
        fields = ['id', 'name', 'code']


class IdTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = IdType
        fields = ['id', 'name', 'code']


class PatientSerializer(serializers.ModelSerializer):
    relation = RelationTypeSerializer()
    id_type = IdTypeSerializer()
    class Meta:
        model = Patient
        fields = '__all__'


class PatientCreateUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Patient
        fields = '__all__'

class SfLoginSerializer(serializers.ModelSerializer):
    class Meta:
        model = Sflogin
        fields = '__all__'

class RechargeOrderSerializer(serializers.ModelSerializer):
    """充值订单序列化器"""
    
    class Meta:
        model = RechargeOrder
        fields = ['order_id', 'patient', 'amount', 'status', 'payment_method', 'payment_time', 'created_at', 'updated_at', 'trade_no']
        read_only_fields = ['order_id', 'status', 'payment_time', 'created_at', 'updated_at', 'trade_no']


class PaymentUrlSerializer(serializers.ModelSerializer):
    """支付链接序列化器"""
    
    class Meta:
        model = PaymentUrl
        fields = ['order', 'url', 'created_at']
        read_only_fields = ['created_at']


class RechargeCreateSerializer(serializers.Serializer):
    """创建充值订单的序列化器"""
    amount = serializers.DecimalField(max_digits=10, decimal_places=2, min_value=Decimal('0.01'))
    patient_id = serializers.IntegerField()
    
    def validate_amount(self, value):
        """验证充值金额"""
        if value <= 0:
            raise serializers.ValidationError("充值金额必须大于0")
        return value
    
    def validate_patient_id(self, value):
        """验证就诊人ID"""
        try:
            Patient.objects.get(id=value)
        except Patient.DoesNotExist:
            raise serializers.ValidationError("就诊人不存在")
        return value
